<script setup lang="ts">
import { postLoginPasswordAPI } from '@/apis/common'
import { useUserStore } from '@/stores/userStore'
import type { PostLoginPasswordParams } from '@/types/common'
import { ref } from 'vue'


const userStore = useUserStore()
defineOptions({
  options: {
    styleIsolation: 'shared',
  },
})

const formData = ref<PostLoginPasswordParams>({
  mobile: '13230000092',
  password: 'abc12345',
})
const formRef = ref<UniHelper.UniFormsInstance>()
const formRules = ref<UniHelper.UniFormsRules>({
  mobile: {
    rules: [
      { required: true, errorMessage: '请输入手机号' },
      { pattern: /^1[3456789]\d{9}$/, errorMessage: '请输入正确的手机号' },
    ],
  },
  password: {
    rules: [{ required: true, errorMessage: '请输入密码' }],
  },
})
const isAgree = ref(false)

const handleLogin = async () => {
  if (!isAgree.value) {
    return uni.showToast({
      title: '请先同意用户协议',
      icon: 'none',
    })
  }
  await formRef.value?.validate?.()
  const res =  await postLoginPasswordAPI(formData.value)
  console.log('res', res)
  userStore.setToken(res.data.token)
  userStore.setUserInfo(res.data)
  uni.showToast({ title: '登录成功', icon: 'success' })
  uni.switchTab({ url: '/pages/index/index'})
}
</script>

<template>
  <uni-forms class="login-form" ref="formRef" :model="formData" :rules="formRules">
    <uni-forms-item name="mobile">
      <uni-easyinput
        :maxlength="11"
        v-model="formData.mobile"
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <uni-easyinput
        v-model="formData.password"
        type="password"
        placeholder="请输入密码"
        :input-border="false"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>
    <view class="agreement">
      <radio :checked="isAgree" @tap="isAgree = !isAgree" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @tap="handleLogin">登 录</button>
    <navigator hover-class="none" class="uni-navigator" url=" "> 忘记密码？ </navigator>
  </uni-forms>
  {{ formData }}{{ isAgree }}
</template>

<style lang="scss">
@import './styles.scss';
</style>
